#include "statuschecker.h"

#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusMessage>
#include <QDBusReply>

#include <QDebug>

#define ADD_STATUS_EMBLEM(A, B) statusEmblemsHash.insert(#A, "emblem-rabbitvcs-"#B)

QDBusInterface *interface = nullptr;
StatusChecker *checker = nullptr;

QHash<QString, QString> statusEmblemsHash;

StatusChecker *StatusChecker::getInstance()
{
    if (!checker) {
        checker = new StatusChecker;
    }
    return checker;
}

QString StatusChecker::checkStatus(const QString &path, bool recurse, bool invalidate, bool summary)
{
   QDBusReply<QString> reply = interface->call("CheckStatus", path.toUtf8(), recurse, invalidate, summary);
   if (reply.error().isValid()) {
       qWarning()<<reply.error().name()<<reply.error().type()<<reply.error().message();
       return nullptr;
   }
   return reply.value();
}

QString StatusChecker::generateMenuConditions(const QStringList &paths)
{
    QList<QVariant> tmp;
    for (QString path : paths) {
        tmp.append(path.toUtf8());
    }
    QDBusReply<QString> reply = interface->call("GenerateMenuConditions", tmp);
    if (reply.error().isValid()) {
        qWarning()<<reply.error().name()<<reply.error().type()<<reply.error().message();
        return nullptr;
    }
    return reply.value();
}

QString StatusChecker::getStatusIconName(const QString &status)
{
    return statusEmblemsHash.value(status);
}

StatusChecker::StatusChecker(QObject *parent) : QObject(parent)
{
    if (!interface) {
        interface = new QDBusInterface(SERVICE, OBJECT_PATH, INTERFACE);
        //statusEmblemsHash.insert("normal", "emblem-rabbitvcs-normal");
        ADD_STATUS_EMBLEM(normal, normal);
        ADD_STATUS_EMBLEM(modified, modified);
        ADD_STATUS_EMBLEM(added, added);
        ADD_STATUS_EMBLEM(deleted, deleted);
        ADD_STATUS_EMBLEM(read-only, locked);
        ADD_STATUS_EMBLEM(locked, locked);
        ADD_STATUS_EMBLEM(unknown, unknown);
        ADD_STATUS_EMBLEM(ignored, ignored);
        ADD_STATUS_EMBLEM(missing, complicated);
        ADD_STATUS_EMBLEM(replaced, modified);
        ADD_STATUS_EMBLEM(complicated, complicated);
        ADD_STATUS_EMBLEM(calculating, calculating);
        ADD_STATUS_EMBLEM(error, error);
        ADD_STATUS_EMBLEM(unversioned, unversioned);
        qDebug()<<statusEmblemsHash;
    }
}
